package com.kx.face.controller;

import com.alibaba.fastjson.JSONObject;
import com.kx.base.dto.face.FaceDTO;
import com.kx.base.result.R;
import com.kx.face.service.FaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 人脸服务的api定义
 *
 * @Author Sun
 * @Date 2021/7/20 23:06
 */
@RestController
@RequestMapping("kx/face")
public class FaceController {

    @Autowired
    private FaceService faceService;

    /**
     * 保存人脸信息的接口
     */
    @PostMapping("save")
    public R save(@RequestBody FaceDTO faceDTO) {
        String face = faceDTO.getFace();
        Long userId = faceDTO.getUserId();
        Integer serviceId=faceDTO.getServiceId();
        if(serviceId==null){
            //请求是非法的
            return R.error(505,"非法请求，请指定serviceId");
        }

        boolean result = faceService.addFace(userId, face,serviceId);
        if (result) {
            return R.ok(200, "人脸保存成功");
        } else {
            return R.error(500, "人脸保存失败");
        }
    }

    /**
     * 删除人脸信息的接口
     */
    @DeleteMapping("delete")
    public R delFace(@RequestBody FaceDTO faceDTO){
        Long userId=faceDTO.getUserId();
        Integer serviceId=faceDTO.getServiceId();
        if(serviceId==null){
            //请求是非法的
            return R.error(505,"非法请求，请指定serviceId");
        }

        //人脸注册
        boolean result=faceService.delFace(userId,serviceId);
        if(result){
            return R.ok("人脸信息删除成功");
        }else{
            return R.error("人脸信息删除失败");
        }
    }

    /**
     * 人脸识别的接口
     */
    @PostMapping("search")
    public R searchFace(@RequestBody FaceDTO faceDTO){
        String face=faceDTO.getFace();
        Integer serviceId=faceDTO.getServiceId();
        if(serviceId==null){
            //请求是非法的
            return R.error(505,"非法请求，请指定serviceId");
        }

        Long userId=faceService.search(face,serviceId);
        if(userId!=null){
            //成功
            JSONObject result=new JSONObject();
            result.put("userId",userId);
            return R.ok(200,"识别成功").setResult(result);
        }else{
            //失败
            return R.ok(500,"识别失败");
        }
    }
}
